/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package moonnms.libs;

import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.common.IOUtils;
import net.schmizz.sshj.connection.channel.direct.Session;
import net.schmizz.sshj.connection.channel.direct.Session.Command;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.schmizz.sshj.connection.ConnectionException;
import net.schmizz.sshj.transport.TransportException;
import net.schmizz.sshj.transport.verification.PromiscuousVerifier;

/**
 *
 * @author Di_Moon
 */
public class libNMSSSHClient {
    private SSHClient ssh = new SSHClient();
    private boolean loginState = false;
    
    public libNMSSSHClient(String server, int port) {
        try {
//            ssh.loadKnownHosts();
            ssh.addHostKeyVerifier(new PromiscuousVerifier());
            ssh.connect(server, port);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    // Аутентификация
    public void login(String user, String pass) {
        try {
            System.out.println("Authenticating...");
            ssh.authPassword(user, pass);
            loginState = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    // Отправка команды и получение результата выполнения
    public String sendCommand(String strCmd) {
        try {
            final Session session = ssh.startSession();
            String strData = "";
            try {
                Command cmd = session.exec(strCmd);
                strData = IOUtils.readFully(cmd.getInputStream()).toString();
            } finally {
                session.close();
                return strData;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return null;
    }
    
    public void disconnect() {
        try {
            ssh.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
